package com.example.demo.arithmetic;

/**
 * Description: 折半查找,给定排序好的数组，查找target相等的元素的下标，不存在返回-1<br/>
 *
 * @author liulonglong
 * @taskId <br/>
 * @Date 2020/3/13 14:49
 * @Version 1.0
 */
public class BinarySearch {

    public static int find(int[] a, int target) {
        int low = 0;
        int high = a.length - 1;
        while (low <= high) {
            int mid = (low + high) >>> 1;
            if (a[mid] == target) {
                return mid;
            } else if (a[mid] > target) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        System.out.println(find(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 19 }, 5));
    }
}
